package cn.wolfcode.crm.serivce.impl;

import cn.wolfcode.crm.domain.*;
import cn.wolfcode.crm.mapper.AccountMapper;
import cn.wolfcode.crm.mapper.StockOutBillItemMapper;
import cn.wolfcode.crm.mapper.StockOutBillMapper;
import cn.wolfcode.crm.mapper.ProductStockMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.serivce.IStockOutBillService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Date;
import java.util.List;


@Service
public class StockOutBillServiceImpl implements IStockOutBillService {
    @Autowired
    private StockOutBillMapper stockOutBillMapper;

    @Autowired
    private StockOutBillItemMapper stockOutBillItemMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    @Autowired
    private AccountMapper accountMapper;//销售帐


    @Override
    public void deleteByPrimaryKey(Long id) {
        //根据单据的ID查询完整的信息
        StockOutBill old = stockOutBillMapper.selectByPrimaryKey(id);
        if(old.getStatus() == StockOutBill.NORMAL){
            stockOutBillMapper.deleteItemByBillId(id);
            stockOutBillMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public void saveOrUpdate(StockOutBill record) {
        if (record.getId() == null) {
            //保存操作
            saveBill(record);
        }else {
            updateBill(record);
        }
    }


    //保存单据
    public void saveBill(StockOutBill record){
        //设置录入人
        record.setInputUser(UserContext.getCurrentuser());
        //设置录入时间
        record.setInputTime(new Date());
        record.setVdate(new Date());
        //设置单据状态
        record.setStatus(StockOutBill.NORMAL);

        //定义变量记录总数量和总价
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;

        //设置明细数据
        for (StockOutBillItem item : record.getItems()) {
            BigDecimal number = item.getNumber();
            BigDecimal salePrice = item.getSalePrice();
            BigDecimal amount = number.multiply(salePrice).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            //叠加总数量和总价
            totalNumber = totalNumber.add(number);
            totalAmount = totalAmount.add(amount);
        }
        record.setTotalNumber(totalNumber);
        record.setTotalAmount(totalAmount);
        //保存单据
        stockOutBillMapper.insert(record);

        //保存明细
        for (StockOutBillItem item : record.getItems()) {
            item.setBillId(record.getId());
            stockOutBillItemMapper.insert(item);
        }

    }

    //更新单据
    public void updateBill(StockOutBill record){
        //根据单据的ID查询完整信息
        StockOutBill old = stockOutBillMapper.selectByPrimaryKey(record.getId());
        //为审核状态才能更新
        if(old.getStatus() == StockOutBill.NORMAL){
            //删除当前所有明细
            stockOutBillMapper.deleteItemByBillId(old.getId());
            //定义变量记录总数量和总价
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            //设置明细数据
            for (StockOutBillItem item : record.getItems()) {
                BigDecimal number = item.getNumber();
                BigDecimal salePrice = item.getSalePrice();
                BigDecimal amount = number.multiply(salePrice).setScale(2, RoundingMode.HALF_UP);
                item.setAmount(amount);
                //叠加总数量和总价
                totalNumber = totalNumber.add(number);
                totalAmount = totalAmount.add(amount);
                item.setBillId(old.getId());
                stockOutBillItemMapper.insert(item);
            }
            old.setTotalNumber(totalNumber);
            old.setTotalAmount(totalAmount);
            //回填
            old.setSn(record.getSn());
            old.setVdate(record.getInputTime());
            old.setMember(record.getMember());
            old.setDepot(record.getDepot());
            stockOutBillMapper.updateByPrimaryKey(old);
        }
    }


    @Override
    public StockOutBill selectByPrimaryKey(Long id) {
        return stockOutBillMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult query(QueryObject qo) {
        Integer total = stockOutBillMapper.count(qo);
        if (total > 0) {
            List<StockOutBill> rows = stockOutBillMapper.query(qo);

            return new PageResult(total,rows);
        }
        return new PageResult(0, Collections.EMPTY_LIST);
    }

    //审核入库
    public void audit(Long id) {
        //根据单据ID查询完整的信息
        StockOutBill bill = stockOutBillMapper.selectByPrimaryKey(id);
        //检查当前单据的状态,未检查才能审核
        if(bill.getStatus() == StockOutBill.NORMAL){
            Depot depot = bill.getDepot();
            //得到当前单据中所有的明细,依次入库
            for (StockOutBillItem item : bill.getItems()) {
                Product p = item.getProduct();
                //查询当前商品所入的仓库中是否拥有该商品的库存
                ProductStock ps = productStockMapper.selectByProductAndDepot(p.getId(), depot.getId());
                if(ps == null){ //2.该商品在该仓库中没有库存
                    String msg = "仓库:[" + depot.getName()+"]没有["+p.getName()+"]商品的库存";
                    throw new RuntimeException(msg);
                }
                //3.检查库存数量是否满足出库的数量
                if (item.getNumber().compareTo(ps.getStoreNumber()) > 0) {
                    String msg = "仓库:["+depot.getName()+p.getName()+"]商品的库存是:"+ps.getStoreNumber()+",不足出库数量"+item.getNumber();
                    throw new RuntimeException(msg);
                }
                //4.满足出库要求,减少总价值,减少总数量
                BigDecimal am = ps.getPrice().multiply(item.getNumber()).setScale(2, RoundingMode.HALF_UP);
                BigDecimal amount = ps.getAmount().subtract(am);
                ps.setAmount(amount);
                BigDecimal number = ps.getStoreNumber().subtract(item.getNumber());
                ps.setStoreNumber(number);
                //更新库存
                productStockMapper.updateByPrimaryKey(ps);
                //记录销售帐
                Account sa = new Account();
                sa.setVdate(new Date());
                sa.setCostPrice(ps.getPrice());
                sa.setNum(item.getNumber());
                sa.setCostAmmount(am);
                sa.setSalePrice(item.getSalePrice());
                sa.setSaleAmmount(item.getSalePrice().multiply(item.getNumber()).setScale(2,RoundingMode.HALF_UP));
                sa.setProduct(p);
                Employee emp = bill.getInputUser();
                sa.setSaleman(emp);
                sa.setMember(bill.getMember());
                accountMapper.insert(sa);

            }
            //核心:填入审核人,审核时间,修改单据状态
            bill.setAuditTime(new Date());
            bill.setAuditor(UserContext.getCurrentuser());
            bill.setStatus(StockOutBill.AUDIT);
            stockOutBillMapper.audit(bill);
        }
    }


}
